# creation d'un QQplot par plaque - a faire pour les cas et pour les controles
qqplot.p<- function (p.names="P", nb_by_graph=4, IC=NULL, status=NULL, outputfile=NULL) #nb_by_graph : nb de plaque par graphique ; status : 1 for controls, 2 for cases
{
	if((nb_by_graph > length(p.names)) | (nb_by_graph==0)) {
		cat ("ERROR : incorrect nb_by_graph \n")
	}
	else{
		# chargement de la fonction plot.QQs
		source("qqmultiple_function.R")

		#  visualisation des p-values des plaques 
		nb_plate <- length(p.names)
		nb_plot <- ifelse(nb_plate%%nb_by_graph == 0, nb_plate%/%nb_by_graph, (nb_plate%/%nb_by_graph)+1)
		nb_page <- ifelse(nb_plot%%4 == 0, nb_plot%/%4, (nb_plot%/%4)+1)
		x<-1
		y<-nb_by_graph

		if(status == 2){
			if(is.null(outputfile)){outputfile <- "qqplot-plaque-cases"}
			# chargement des donnees
			pval <- read.table(file="p-values-cases.txt",h=T)
		}
		if(status == 1){
		if(is.null(outputfile)){outputfile <- "qqplot-plaque-controls"}
			# chargement des donnees
			pval <- read.table(file="p-values-controls.txt",h=T)
		}

		for (k in 1:nb_page){
				png(paste(outputfile,k,".png", sep=""), width=940, height=940, res=72)
				par(mfrow=c(2,2))		

				if(nb_page >1){
					if (k < nb_page){
						for (j in 1:4){ 
							plot.QQs(data1=pval,pobs.name=p.names[x:y],IC=IC)
							nb_plot <- nb_plot-1
							x<-x+nb_by_graph
							y <- y+nb_by_graph
						}
					}
					else{
						if(y > length(p.names)){y<-length(p.names)}	
						for (i in 1:(nb_plot)){
							plot.QQs(data1=pval,pobs.name=p.names[x:y],IC=IC)
							nb_plot <- nb_plot-1
							x <- x+nb_by_graph
							if((y+nb_by_graph) < length(p.names)){y <- y+nb_by_graph}
							else if(x <= length(p.names)){
								y <- length(p.names)
								plot.QQs(data1=pval,pobs.name=p.names[x:y],IC=IC)
								nb_plot <- nb_plot-1
								break
							}
						}
					}
				}
				else{
					for (h in 1:nb_plot){ 
						plot.QQs(data1=pval,pobs.name=p.names[x:y],IC=IC)
						x <- x+nb_by_graph
						if((y+nb_by_graph) < length(p.names)){y <- y+nb_by_graph}
						else if(x <= length(p.names)){
							y<- length(p.names)
							plot.QQs(data1=pval,pobs.name=p.names[x:y],IC=IC)
							break
						}
					}
				}
				dev.off()
		}
	}
}
